# -*- coding: utf-8 -*-
# @copyright Copyright (c) 2022 OnMicro Corp.
# @brief     SNC Field Oriented Control algorithm test: plot .csv exported from jscope.
# @author    wei.lu@onmicro.com.cn
# @license   SPDX-License-Identifier: Apache-2.0

import csv
from collections import namedtuple
import matplotlib.pyplot as plt

def csv_file_data(filename, lines_max):
    index = []
    Valpha = []
    Vbeta = []
    Ialpha = []
    Ibeta = []
    Angle = []
    Ialpha_est = []
    Ibeta_est = []
    Ealpha = []
    Ebeta = []
    Zalpha = []
    Zbeta = []
    lines = 0
    # get filename's suffix: base at [0], suffix at [1]
    suffix = os.path.splitext(filename)[1].lower()
    if suffix == ".csv":
        # Eliminate _csv.Error: field larger than field limit (131072)
        csv.field_size_limit(500*1024*1024)
        with open(filename, encoding='utf-8') as csvfile:
            reader = csv.reader(csvfile, quotechar='#', delimiter=';')
            # Valpha;Vbeta;Ialpha;Ibeta;Aest;Ialpha_est;Ibeta_est;Ealpha;Ebeta;Zalpha;Zbeta
            headers = next(reader)
            Row = namedtuple('Row', headers)
            for r in reader:
                row = Row(*r)
                #print(row.Timestamp, row.Valpha, row.Vbeta)
                #timestamp.append(row.Timestamp)
                index.append(lines)
                Valpha.append(int(row.Valpha))
                Vbeta.append(int(row.Vbeta))
                Ialpha.append(int(row.Ialpha))
                Ibeta.append(int(row.Ibeta))
                Angle.append(int(row.Aest))
                Ialpha_est.append(int(row.Ialpha_est))
                Ibeta_est.append(int(row.Ibeta_est))
                Ealpha.append(int(row.Ealpha))
                Ebeta.append(int(row.Ebeta))
                Zalpha.append(int(row.Zalpha))
                Zbeta.append(int(row.Zbeta))
                lines = lines + 1
                if lines >= lines_max:
                    break
    else:
        print("unsupported file format")
        sys.exit(1)
    return index, Valpha, Vbeta, Ialpha, Ibeta, Angle, Ialpha_est, Ibeta_est, Ealpha, Ebeta, Zalpha, Zbeta

if __name__ == "__main__":
    import os,sys
    if not (len(sys.argv)>1 and os.path.isfile(sys.argv[1])):
        print('usage: {} jscope_export.csv lines'.format(sys.argv[0]))
        sys.exit(1)
    lines_max = 2048
    if (len(sys.argv)>2):
        lines_max = int(sys.argv[2])

    # ebf_snc_py32f0_Aest_Valpha_Vbeta_Ialpha_Ibeta_startup.csv
    # ebf_snc_stm32f407_Aest_Valpha_Vbeta_Ialpha_Ibeta_smc.csv
    index, Valpha, Vbeta, Ialpha, Ibeta, Angle, Ialpha_est, Ibeta_est, Ealpha, Ebeta, Zalpha, Zbeta = csv_file_data(sys.argv[1], lines_max)

    fig = plt.figure()
    # numRows=2, numCols=1
    plt.subplot(211)
    plt.title('SMC waveform alpha/beta')
    plt.ylabel('V/A')
    plt.plot(index, Angle,  c='grey', label='angle', alpha=0.5)
    plt.plot(index, Valpha,     c='red',    label='Valpha')
    plt.plot(index, Ialpha,     c='green',  label='Ialpha',     alpha=0.5)
    plt.plot(index, Ialpha_est, c='green',  label='Ialpha_est', alpha=0.5)
    plt.plot(index, Ealpha,     c='red',    label='Ealpha',     alpha=0.5)
    plt.plot(index, Zalpha,     c='yellow', label='Zalpha',     alpha=0.3)
    plt.grid()
    plt.legend()

    plt.subplot(212)
    plt.ylabel('V/A')
    plt.xlabel('FOC step')
    plt.plot(index, Angle,  c='grey', label='angle', alpha=0.5)
    plt.plot(index, Vbeta,      c='red',    label='Vbeta')
    plt.plot(index, Ibeta,      c='green',  label='Ibeta',      alpha=0.5)
    plt.plot(index, Ibeta_est,  c='green',  label='Ibeta_est',  alpha=0.5)
    plt.plot(index, Ebeta,      c='red',    label='Ebeta',      alpha=0.5)
    plt.plot(index, Zbeta,      c='yellow', label='Zbeta',      alpha=0.3)
    #plt.axhline(0, color='black')
    plt.grid()
    plt.legend()

    plt.show()
